//
//  LFBHomeController.m
//  loveFreshBeen
//
//  Created by Feng on 2017/7/9.
//  Copyright © 2017年 feng. All rights reserved.
//

#import "LFBHomeController.h"
#import "LFBNetworkManager.h"
#import "LFBHomeHeaderView.h"
#import "LFBHomeLabelView.h"
#import "LFBCycleModel.h"
#import "LFBIconModel.h"
#import "LFBActivityModel.h"
#import "LFBWebViewController.h"
#import "LFBHomeHeaderViewCell.h"
#import "LFBHomeLabelViewCell.h"
#import "LFBShoppingCartModel.h"
#import "LFBDetailProductInfoController.h"
#import "LFBLeftBarButtonItemCustomView.h"
#import "LFBIphoneScanQRCodeController.h"
#import "LFBSimulatorScanQRCodeController.h"
#import "LFBRightBarButtonItemCustomView.h"
#import "LFBSearchController.h"
#import <Masonry.h>
#import <YYModel.h>
#import <MJRefresh.h>

@interface LFBHomeController ()<UICollectionViewDelegateFlowLayout>

//轮播器数据
@property(nonatomic,strong) NSArray *focusArray;
//图标数据
@property(nonatomic,strong) NSArray *iconsArray;
//活动数据
@property(nonatomic,strong) NSArray *activityDataArray;
//新鲜热卖数据
@property(nonatomic,strong) NSArray *novelSaleArray;
//布局对象
@property(nonatomic,strong) UICollectionViewFlowLayout *flowLayout;
//第0组头部视图
@property(nonatomic,strong) LFBHomeHeaderView *homeHeaderView;

//test
@property(nonatomic,strong) UIView *subView;

//@property(nonatomic,strong) LFBHomeHeaderFlowLayout *headerFlowLayout;
//@property(nonatomic,strong) LFBHomeLabelFlowLayout *labelFlowLayout;

@end

static NSString *HomeCycleID = @"HomeCycleID";
static NSString *HomeIconID = @"HomeIconID";
static NSString *HeaderCell = @"HeaderCell";
static NSString *LabelCell = @"LabelCell";

@implementation LFBHomeController

- (instancetype)init
{
    self = [super init];
    if (self) {
        //设置LeftBatButtonItem
        [self setLeftBatButtonItem];
        
        //设置rightBarButtonItem
        [self setRightBarButtonItem];
        
        //设置collectionView
        [self setupCollectionView];
        
        //设置发送通知
        [self setupNotifications];
        
        //加载数据
        [self loadData];
        
        //设置下拉刷新,上拉加载
        [self setupRefresh];
    }
    return self;
}

/*
 在init的方法里面注册可重用ID,因为此时Viewdidload方法已经不再执行...具体原因 还不清楚
 */
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)setupUI
{
//    [self setupNotifications];
//    [self loadData];
//    [self setupTableView];
}

- (void)setupRefresh
{
//    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNovelSALEData)];
//
//    [self.collectionView.mj_header beginRefreshing];
    
    //设置刷新图片
    UIImage *refresh1 = [UIImage imageNamed:@"v2_pullRefresh1"];
    UIImage *refresh2 = [UIImage imageNamed:@"v2_pullRefresh2"];
    NSArray<UIImage *> *idleImages = @[refresh1];
    NSArray<UIImage *> *pullingImages = @[refresh2];
    NSArray<UIImage *> *refreshingImages = @[refresh1,refresh2];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNovelSALEData)];
    // 设置普通状态的动画图片 (idleImages 是图片)
    [header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    //隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    // 设置header
    self.collectionView.mj_header = header;
    
    //上拉加载
//    self.collectionView.mj_footer
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadNovelSALEData];
    }];
}

- (void)setupCollectionView
{
    /** 创建布局参数 */
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout = flowLayout;

    /**
     1.创建collectionView
     2.设置布局参数
     */
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    
    //注册头部是图
//    [self.collectionView registerClass:[LFBHomeHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HomeCycleID];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HomeCycleID];
    [self.collectionView registerClass:[LFBHomeLabelView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HomeIconID];
    
    flowLayout.headerReferenceSize = CGSizeMake(260, 260);
    
    /** 注册cell可重用ID */
    [self.collectionView registerClass:[LFBHomeHeaderViewCell class] forCellWithReuseIdentifier:HeaderCell];
//    [self.collectionView registerClass:[LFBHomeLabelViewCell class] forCellWithReuseIdentifier:LabelCell];
    [self.collectionView registerNib:[UINib nibWithNibName:@"LFBHomeLabelViewCell" bundle:nil] forCellWithReuseIdentifier:LabelCell];
    
    self.collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

- (void)setLeftBatButtonItem
{
    LFBLeftBarButtonItemCustomView *customView = [LFBLeftBarButtonItemCustomView leftBarButtonItemCustomView];
    customView.backgroundColor = [UIColor clearColor];
    customView.frame = CGRectMake(0, 0, 40, 40);
    [customView addTarget:self action:@selector(leftBarButtonItemAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
}

- (void)leftBarButtonItemAction:(LFBLeftBarButtonItemCustomView *)customView
{
    if(TARGET_IPHONE_SIMULATOR)
    {
        LFBSimulatorScanQRCodeController *simulatorVC = [LFBSimulatorScanQRCodeController new];
        simulatorVC.view.backgroundColor = [UIColor lightGrayColor];
        [self.navigationController pushViewController:simulatorVC animated:YES];
    }
    else if(TARGET_OS_IPHONE)
    {
        LFBIphoneScanQRCodeController *iphoneVC = [LFBIphoneScanQRCodeController new];
        [self.navigationController pushViewController:iphoneVC animated:YES];
        NSLog(@"~~手机");
    }
}

- (void)setRightBarButtonItem
{
    LFBRightBarButtonItemCustomView *customView = [LFBRightBarButtonItemCustomView rightBarButtonItemCustomView];
    customView.backgroundColor = [UIColor clearColor];
    customView.frame = CGRectMake(0, 0, 40, 40);
    [customView addTarget:self action:@selector(rightBarButtonItemAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
}

- (void)rightBarButtonItemAction:(LFBRightBarButtonItemCustomView *)customView
{
    LFBSearchController *searchVC = [LFBSearchController new];
    searchVC.view.backgroundColor = [UIColor whiteColor];
    
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)setupNotifications
{
    //注册轮播器通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeCycleViewDidSelectedNotification:) name:LFBHomeCycleViewDidSelectedNotification object:nil];
    //注册中间icon点击通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeIconButtonDidClickNotification:) name:LFBHomeIconButtonDidClickNotification object:nil];
    //注册搜索页面点击数量增减通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchResultNumChangeNotification:) name:LFBSearchResultNumChangeNotification object:nil];
}

- (void)searchResultNumChangeNotification:(NSNotification *)noti
{
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
}

- (void)teardownNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc
{
    [self teardownNotifications];
}

//通知监听方法
- (void)homeCycleViewDidSelectedNotification:(NSNotification *)noti
{
    [self jumpToWebViewControllerWithURLStr:noti.userInfo[KHomeCycleViewURL]];
}

- (void)homeIconButtonDidClickNotification:(NSNotification *)noti
{
    [self jumpToWebViewControllerWithURLStr:noti.userInfo[KHomeIconButtonURL]];
}

- (void)jumpToWebViewControllerWithURLStr:(NSString *)URLStr
{
    LFBWebViewController *webViewVC = [LFBWebViewController new];
    webViewVC.URLStr = URLStr;
    
    [self.navigationController pushViewController:webViewVC animated:YES];
}

#pragma - UICollectionViewDataSource -
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return self.activityDataArray.count;
    }
    else
    {
        return self.novelSaleArray.count;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        LFBHomeHeaderViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HeaderCell forIndexPath:indexPath];
        cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        cell.model = self.activityDataArray[indexPath.item];
        
        return cell;
    }
    else
    {
        LFBHomeLabelViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:LabelCell forIndexPath:indexPath];
        cell.backgroundColor = [UIColor yellowColor];
        
        LFBShoppingCartModel *model = self.novelSaleArray[indexPath.item];
        
        cell.model = model;
        
        cell.clickProductView.productCount = [[LFBShoppingCartManager sharedManager] productCountWithShoppingCartModelID:model.product_id];
        
        return cell;
    }
}

//设置头部视图样式
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        if(self.homeHeaderView == nil)
        {
            self.homeHeaderView = [[LFBHomeHeaderView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        }
        
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HomeCycleID forIndexPath:indexPath];
        
        [view addSubview:self.homeHeaderView];
        
        return view;
    }
    else
    {
        LFBHomeLabelView *homeLabelView = [[LFBHomeLabelView alloc] init];
        
        homeLabelView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HomeIconID forIndexPath:indexPath];
        
        return homeLabelView;
    }
}

//点击item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        LFBActivityModel *model = self.activityDataArray[indexPath.item];
        
        [self jumpToWebViewControllerWithURLStr:model.customURL];
    }
    else
    {
        LFBDetailProductInfoController *detailProductInfoVC = [LFBDetailProductInfoController new];
        
        //获取对应cell的model
        LFBHomeLabelViewCell *cell = (LFBHomeLabelViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        //有可能模型数据一样,但是地址不一样
        detailProductInfoVC.shoppingCartModel = [[LFBShoppingCartManager sharedManager] shoppingCartModelWithModelID:cell.model.product_id];
        
        [self.navigationController pushViewController:detailProductInfoVC animated:YES];
    }
}

//cell即将显示
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1 && indexPath.item > 1)
    {
        cell.transform = CGAffineTransformMakeTranslation(0, 60);
        
        [UIView animateWithDuration:1.0 animations:^{
            cell.transform = CGAffineTransformIdentity;
        }];
    }
}

//cell即将消失
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{

}

#pragma - UICollectionViewDelegateFlowLayout 代理方法-
//设置头部视图大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if(section == 1)
    {
        return CGSizeMake(50, 50);
    }
    return CGSizeMake(260, 260);
}

//设置item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return CGSizeMake(ScreenWidth - Margin * 2, 150);
    }
    else
    {
        return CGSizeMake((ScreenWidth - Margin * 3) / 2, 340);
    }
}

//设置item与视图间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if(section == 0)
    {
        return UIEdgeInsetsMake(Margin, Margin, 0, Margin);
    }
    else if(section == 1)
    {
        return UIEdgeInsetsMake(0, Margin, 0, Margin);
    }
   
    return UIEdgeInsetsZero;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if(section == 1)
    {
        return Margin;
    }
    
    return Margin;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return Margin;
}

- (void)loadData
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadHomeData];
        [self loadNovelSALEData];
    });
}

- (void)loadHomeData
{
    [LFBNetworkManager getHomeData:^(id responseObject) {
        
        NSDictionary *dataDict = responseObject[@"data"];
        NSArray *focusArray = [NSArray yy_modelArrayWithClass:[LFBCycleModel class] json:dataDict[@"focus"]];
        NSArray *iconsArray = [NSArray yy_modelArrayWithClass:[LFBIconModel class] json:dataDict[@"icons"]];
        NSArray *activitiesArray = [NSArray yy_modelArrayWithClass:[LFBActivityModel class] json:dataDict[@"activities"]];
        
        self.homeHeaderView.focusArray = focusArray;
        self.homeHeaderView.iconsArray = iconsArray;
        
        self.activityDataArray = activitiesArray;
        
        [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        
    } failure:^(NSError *error) {
        
        if(error != nil)
        {
            NSLog(@"error = %@",error);
        }
    }];
}

- (void)loadNovelSALEData
{
    [LFBNetworkManager getNovelSALEData:^(id responseObject) {
        
        NSArray<LFBShoppingCartModel *> *dataArray = [NSArray yy_modelArrayWithClass:[LFBShoppingCartModel class] json:responseObject[@"data"]];
        
        self.novelSaleArray = dataArray;
        
        //增入到单例模型数组
        [dataArray enumerateObjectsUsingBlock:^(LFBShoppingCartModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [[LFBShoppingCartManager sharedManager] addShoppingCartProductWithProdunctModel:obj andIsFirstTime:YES];
        }];
        
        [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
        
        //结束刷新
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(NSError *error) {
        
        if(error != nil)
        {
            NSLog(@"error = %@",error);
        }
    }];

}

@end
